package com.coursehub.exercise.service.impl;

import com.coursehub.exercise.entity.WrongQuestionBank;
import com.coursehub.exercise.entity.WrongQuestionBankQuestion;
import com.coursehub.exercise.entity.WrongQuestionBankQuestionId;
import com.coursehub.exercise.repository.WrongQuestionBankQuestionRepository;
import com.coursehub.exercise.repository.WrongQuestionBankRepository;
import com.coursehub.exercise.service.WrongQuestionBankService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional
public class WrongQuestionBankServiceImpl implements WrongQuestionBankService {

    private final WrongQuestionBankRepository wrongQuestionBankRepository;
    private final WrongQuestionBankQuestionRepository wrongQuestionBankQuestionRepository;

    @Override
    public WrongQuestionBank create(String wrongQuestionBankId, String userId, String courseId) {
        WrongQuestionBank bank = new WrongQuestionBank();
        bank.setWrongQuestionBankId(wrongQuestionBankId);
        bank.setUserId(userId);
        bank.setCourseId(courseId);
        return wrongQuestionBankRepository.save(bank);
    }

    @Override
    public void delete(String wrongQuestionBankId) {
        wrongQuestionBankRepository.deleteById(wrongQuestionBankId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<WrongQuestionBank> listByUser(String userId) {
        return wrongQuestionBankRepository.findByUserId(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<WrongQuestionBank> listByUserAndCourse(String userId, String courseId) {
        return wrongQuestionBankRepository.findByUserIdAndCourseId(userId, courseId);
    }

    @Override
    public void addQuestion(String wrongQuestionBankId, String questionId) {
        if (wrongQuestionBankQuestionRepository.existsByIdWrongQuestionBankIdAndIdQuestionId(wrongQuestionBankId, questionId)) {
            return;
        }
        WrongQuestionBankQuestion entity = new WrongQuestionBankQuestion();
        entity.setId(new WrongQuestionBankQuestionId(wrongQuestionBankId, questionId));
        wrongQuestionBankQuestionRepository.save(entity);
    }

    @Override
    public void removeQuestion(String wrongQuestionBankId, String questionId) {
        wrongQuestionBankQuestionRepository.deleteByIdWrongQuestionBankIdAndIdQuestionId(wrongQuestionBankId, questionId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> listQuestionIds(String wrongQuestionBankId) {
        return wrongQuestionBankQuestionRepository.findByIdWrongQuestionBankId(wrongQuestionBankId)
                .stream().map(e -> e.getId().getQuestionId()).collect(Collectors.toList());
    }
}


